<template>
  <div class="app-container" style="width: 600px">
    <el-form
      :model="form"
      status-icon
      :rules="rules"
      ref="form"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="插入时间" prop="timeSpan">
        <el-date-picker
          v-model="form.timeSpan"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="观看记录数量" prop="viewCount">
        <el-input type="number" v-model.number="form.viewCount"></el-input>
        <el-button
          v-if="!videoIds.length"
          type="primary"
          style="margin-left: 8px"
          @click="showvideo"
          >关联视频</el-button
        >
        <el-button
          v-else
          type="primary"
          style="margin-left: 8px"
          @click="showvideo"
          >已选({{ videoIds.length }})</el-button
        >
      </el-form-item>
      <el-form-item label="答题记录数量" prop="answerCount">
        <el-input type="number" v-model.number="form.answerCount"></el-input>
        <el-button
          v-if="!topicIds.length"
          type="primary"
          @click="showTopic"
          style="margin-left: 8px"
          >关联试题</el-button
        >
        <el-button
          v-else
          type="primary"
          style="margin-left: 8px"
          @click="showTopic"
          >已选({{ topicIds.length }})</el-button
        >
      </el-form-item>
      <el-form-item label="下载试题数量" prop="downloadCount">
        <el-input type="number" v-model.number="form.downloadCount"></el-input>
        <el-button
          v-if="!selectDownload.length"
          type="primary"
          @click="showDownTopic"
          style="margin-left: 8px"
          >关联题库</el-button
        >
        <el-button
          v-else
          type="primary"
          style="margin-left: 8px"
          @click="showDownTopic"
          >已选({{ selectDownload.length }})</el-button
        >
      </el-form-item>

      <el-form-item label="学生注册数" prop="userCount">
        <el-input type="number" v-model.number="form.userCount"></el-input>
      </el-form-item>
      <el-form-item label="选择学校" prop="deptId">
        <el-select
          v-model="form.deptId"
          placeholder="请选择"
          filterable
          @change="selectChange"
        >
          <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="关联视频"
      :visible.sync="videoDialog"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      fullscreen
    >
      <el-form
        :model="videoParams"
        ref="queryForm1"
        size="small"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="课程名称" prop="title">
          <el-input
            v-model="videoParams.title"
            placeholder="请输入课程名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="讲师" prop="Lecturer">
          <el-input
            v-model="videoParams.Lecturer"
            placeholder="请输入讲师"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <md-select-tree
            v-model="videoParams.categoryId"
            :defaultExpandAll="true"
            :data="parentList"
            nodeKey="rid"
            :defaultProps="{ label: 'name', children: 'categoryList' }"
            placeholder="请选择上级"
          ></md-select-tree>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isNominate">
          <el-select
            v-model="videoParams.isNominate"
            placeholder="是否推荐"
            clearable
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否首页" prop="isHome">
          <el-select
            v-model="videoParams.isHome"
            placeholder="是否首页"
            clearable
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="videoParams.status" placeholder="状态" clearable>
            <el-option label="显示" value="1"></el-option>
            <el-option label="隐藏" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getListVideo"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="videoResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="videoList"
        height="60vh"
        row-key="rid"
        @selection-change="handleVideoTableSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
          align="left"
        />
        <el-table-column label="编号" align="left" prop="rid" width="50" />

        <el-table-column
          label="课程名称"
          align="left"
          prop="title"
          min-width="380"
        />

        <el-table-column label="讲师" align="left" prop="lecturer" />

        <el-table-column label="创建时间" align="left" prop="createTime" />
      </el-table>

      <pagination
        v-show="videoTotal > 0"
        :total="videoTotal"
        :page.sync="videoParams.pageNum"
        :limit.sync="videoParams.pageSize"
        @pagination="getListVideo"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFenPeiForm">完成</el-button>
        <el-button @click="cancelFenPei">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="关联题库"
      :visible.sync="topicDialog"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      fullscreen
    >
      <el-form
        :model="topicParams"
        ref="queryForm1"
        size="small"
        :inline="true"
        label-width="68px"
      >
        <!-- <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getListVideo"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="videoResetQuery"
              >重置</el-button
            >
          </el-form-item> -->
      </el-form>

      <el-table
        v-loading="loading"
        ref="multipleTableTopic"
        :data="topicList"
        height="60vh"
        row-key="rid"
        @selection-change="handleTopicTableSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
          align="left"
        />
        <el-table-column label="编号" align="left" prop="rid" width="50" />

        <el-table-column
          label="课程名称"
          align="left"
          prop="title"
          min-width="380"
        />

        <el-table-column label="讲师" align="left" prop="lecturer" />

        <el-table-column label="创建时间" align="left" prop="createTime" />
      </el-table>

      <pagination
        v-show="topicTotal > 0"
        :total="topicTotal"
        :page.sync="topicParams.pageNum"
        :limit.sync="topicParams.pageSize"
        @pagination="getlistAnswer"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTopicForm">完成</el-button>
        <el-button @click="cancelTopic">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联下载记录 -->
    <el-dialog
      title="关联题"
      :visible.sync="DownLoadDialog"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      fullscreen
    >
      <el-form
        :model="topicParams"
        ref="queryForm1"
        size="small"
        :inline="true"
        label-width="68px"
      >
        <!-- <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getListVideo"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="videoResetQuery"
              >重置</el-button
            >
          </el-form-item> -->
      </el-form>

      <el-table
        v-loading="loading"
        ref="multipleTableDown"
        :data="topicList"
        height="60vh"
        row-key="rid"
        @selection-change="handleDownTableSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
          align="left"
        />
        <el-table-column label="编号" align="left" prop="rid" width="50" />

        <el-table-column
          label="课程名称"
          align="left"
          prop="title"
          min-width="380"
        />

        <el-table-column label="讲师" align="left" prop="lecturer" />

        <el-table-column label="创建时间" align="left" prop="createTime" />
      </el-table>

      <pagination
        v-show="topicTotal > 0"
        :total="topicTotal"
        :page.sync="topicParams.pageNum"
        :limit.sync="topicParams.pageSize"
        @pagination="getlistDownloadAnswer"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDownLoadForm">完成</el-button>
        <el-button @click="cancelTopic">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { postoptimize } from "@/api/system/statistics";
import { listVideo } from "@/api/web/video";
import { listAnswer } from "@/api/web/answer";
import { listCategory } from "@/api/web/category";
import { Loading } from "element-ui";
export default {
  name: "Optimize",
  data() {
    return {
      // 表单参数
      form: {
        // viewCount:1,
        // answerCount:1
      },
      queryParams: {
        parentId: 0,
      },
      deptList: [], //用户列表
      // 表单校验
      rules: {
        // viewCount: [
        //   { required: true, message: "请填写观看记录", trigger: "blur" },
        // ],
        // downloadCount: [
        //   { required: true, message: "请填写下载记录", trigger: "blur" },
        // ],
        // answerCount: [
        //   { required: true, message: "请填写答题记录", trigger: "blur" },
        // ],

        deptId: [{ required: true, message: "请选择学校", trigger: "change" }],
      },
      videoDialog: false,
      topicDialog: false,
      DownLoadDialog: false,
      videoParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null,
      },
      topicParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        type: null,
      },
      submitParams: {
        deptId: [],
        rid: [],
      },
      submitTopicParams: {
        deptId: [],
        rid: [],
      },
      submitDownLoadParams: {
        deptId: [],
        rid: [],
      },
      selectVideos: [],
      selectTopic: [],
      selectDownload: [],
      videoList: [],
      topicList: [],
      topicTotal: 0,
      videoTotal: 0,
      parentList: [],
      videoIds: [],
      topicIds: [],
      // 遮罩层
      loading: true,
      ignoreSelectionChange: false,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    videoIds(newValue, old) {
      console.log(newValue, old, "fdfsfdf------------------------->");
    },
  },

  methods: {
    showvideo() {
      this.getListVideo();
      this.getParentList();
      this.videoDialog = true;
    },
    showTopic() {
      this.getlistAnswer();
      this.getParentListTopic();
      this.topicDialog = true;
    },
    showDownTopic() {
      this.getlistDownloadAnswer();
      this.getParentListTopic();
      this.DownLoadDialog = true;
    },
    submitTopicForm() {
      try {
        if (this.selectTopic.length === 0) {
          this.$modal.msgWarning("请选择课程");
          return;
        }
        this.topicIds = [...this.selectTopic];
        this.topicDialog = false;
      } catch (error) {
        console.log(error);
      }
    },
    submitDownLoadForm() {
      try {
        if (this.selectDownload.length === 0) {
          this.$modal.msgWarning("请选择课程");
          return;
        }
        this.DownLoadDialog = false;
      } catch (error) {
        console.log(error);
      }
    },
    /** 查询题库分类列表 */
    getParentListTopic(flag) {
      listCategory({
        type: 2,
      }).then((response) => {
        this.parentList = [];
        if (!flag) {
          const menu = { rid: 0, name: "主类目", categoryList: [] };
          menu.categoryList = response.data;
          this.parentList.push(menu);
        } else {
          this.parentList = response.data;
        }
      });
    },
    /** 查询分类列表 */
    getParentList() {
      listCategory({
        type: 1,
      }).then((response) => {
        this.parentList = response.data;
      });
    },
    videoResetQuery() {
      this.resetForm("queryForm1");
      this.getListVideo(this.submitParams.deptId[0]);
    },
    selectChange(e) {
      console.log(e, "e");
    },
    handleDownTableSelectionChange(event) {
      if (!this.ignoreSelectionChange) {
        this.selectDownload = [
          ...new Set(
            event
              .map((m) => {
                return m.rid;
              })
              .concat(this.submitDownLoadParams.rid)
          ),
        ];
      }
      console.log(this.selectDownload, " this.selectDownload");
      this.ignoreSelectionChange = false;
    },
    handleVideoTableSelectionChange(event) {
      if (!this.ignoreSelectionChange) {
        this.selectVideos = [
          ...new Set(
            event
              .map((m) => {
                return m.rid;
              })
              .concat(this.submitParams.rid)
          ),
        ];
        this.videoIds = this.selectVideos;
      }

      this.ignoreSelectionChange = false;
    },
    handleTopicTableSelectionChange(event) {
      if (!this.ignoreSelectionChange) {
        this.selectTopic = [
          ...new Set(
            event.map((m) => m.rid).concat(this.submitTopicParams.rid)
          ),
        ];
        this.topicIds = [...this.selectTopic];
      }

      // 重置标志，如果需要的话
      this.ignoreSelectionChange = false;
    },
    async getlistAnswer() {
      try {
        const res = await listAnswer(this.topicParams);

        this.topicList = res.rows;
        this.topicTotal = res.total;

        this.$nextTick(() => {
          if (this.ignoreSelectionChange) {
            this.$refs.multipleTableTopic.clearSelection();

            if (this.topicIds && this.topicIds.length > 0) {
              this.topicIds.forEach((id, index) => {
                const row = this.topicList.find((e) => e.rid == id);
                if (row) {
                  this.$refs.multipleTableTopic.toggleRowSelection(row, true);
                } else {
                  this.$refs.multipleTableTopic.toggleRowSelection(row, false);
                }

                if (index === this.selectTopic.length - 1) {
                  this.loading = false;
                }
              });
            }
          }
        });
      } catch (error) {
        console.log(error, "error");
      }
      this.loading = false;
    },
    async getlistDownloadAnswer() {
      try {
        const res = await listAnswer(this.topicParams);

        this.topicList = res.rows;
        this.topicTotal = res.total;

        this.$nextTick(() => {
          if (this.ignoreSelectionChange) {
            this.$refs.multipleTableDown.clearSelection();

            if (this.selectDownload && this.selectDownload.length > 0) {
              this.selectDownload.forEach((id, index) => {
                const row = this.topicList.find((e) => e.rid == id);
                if (row) {
                  this.$refs.multipleTableDown.toggleRowSelection(row, true);
                } else {
                  this.$refs.multipleTableDown.toggleRowSelection(row, false);
                }

                if (index === this.selectDownload.length - 1) {
                  this.loading = false;
                }
              });
            }
          }
        });
      } catch (error) {
        console.log(error, "error");
      }
      this.loading = false;
    },
    async getListVideo() {
      this.loading = true;
      try {
        const res = await listVideo(this.videoParams);

        this.videoList = res.rows;
        this.videoTotal = res.total;

        this.$nextTick(() => {
          console.log(this.ignoreSelectionChange, "ignoreSelectionChange");
          if (this.ignoreSelectionChange) {
            this.$refs.multipleTable.clearSelection();

            if (this.videoIds && this.videoIds.length > 0) {
              this.videoIds.forEach((id, index) => {
                const row = this.videoList.find((e) => e.rid == id);
                if (row) {
                  this.$refs.multipleTable.toggleRowSelection(row, true);
                } else {
                  this.$refs.multipleTable.toggleRowSelection(row, false);
                }

                if (index === this.videoIds.length - 1) {
                  this.loading = false;
                }
              });
            }
          }
        });
      } catch (error) {
        console.log(error);
      }
      this.loading = false;
    },
    async submitFenPeiForm() {
      try {
        if (this.selectVideos.length === 0) {
          this.$modal.msgWarning("请选择课程");
          return;
        }
        this.videoIds = this.selectVideos;
        this.videoDialog = false;
      } catch (error) {
        console.log(error);
      }
    },
    cancelFenPei() {
      this.submitParams = {
        deptId: [],
        rid: [],
      };
      this.videoDialog = false;

      this.videoList = [];
      this.videoTotal = 0;
      this.videoParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null,
      };
      this.videoDialog = false;
      // this.$refs.multipleTableTopic.clearSelection();
      // this.$refs.multipleTable.clearSelection()
    },
    cancelTopic() {
      this.submitTopicParams = {
        deptId: [],
        rid: [],
      };

      this.topicTotal = 0;
      this.topicParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        type: null,
      };

      this.topicDialog = false;
    },
    cancelDown() {
      this.submitDownLoadParams = {
        deptId: [],
        rid: [],
      };

      this.topicTotal = 0;
      this.topicParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        type: null,
      };

      this.topicDialog = false;
    },
    /** 查询组织列表 */
    getList() {
      //   this.loading = true;
      listDept(this.queryParams).then((response) => {
        this.deptList = response.data;
        // this.total = response.total;
        // this.loading = false;
      });
    },
    submitForm() {
      if (this.form.answerCount && this.selectTopic.length == 0) {
        this.$modal.msgWarning("添加答题记录后，请添加具体的题库");
        return;
      }
      if (this.form.viewCount && this.selectVideos.length == 0) {
        this.$modal.msgWarning("添加观看记录后请关联课程");
        return;
      }
      if (this.form.downloadCount && this.selectDownload.length == 0) {
        this.$modal.msgWarning("添加试题下载记录后，请添加具体的题库");
        return;
      }
      this.postoptimizeData({
        ...this.form,
        videoIds: this.videoIds,
        answerIds: this.topicIds,
        downloadIds: this.selectDownload,
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
    },
    async postoptimizeData(date) {
      let loadingInstance = Loading.service({
        lock: true,
        fullscreen: true,
        text: "数据提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.4)",
      });
      this.$refs["form"].validate((valid) => {
        if (valid) {
          postoptimize({
            ...date,
            downloadCount: Number(date.downloadCount),
            viewCount: Number(date.viewCount),
          }).then((response) => {
            loadingInstance.close();
            if (response.code == 200) {
              this.$modal.msgSuccess("操作成功");
              this.ignoreSelectionChange = true;
              this.selectVideos = [];
              this.selectTopic = [];
              this.topicIds = [];
              this.videoIds = [];

              this.$refs["form"].resetFields();
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.btn {
  display: inline-block;
  background-color: #46a6ff;
  color: #fff;
  padding: 5px;
  border-radius: 4px;
  font-size: 14px;
}
::v-deep {
  .el-input {
    width: 60%;
  }
  .el-select {
    width: 100%;
  }
}
</style>
